package fr.isima.gui;

import java.text.SimpleDateFormat;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import fr.isima.R;
import fr.isima.data.TrackProviderAdapter;
import fr.isima.gui.maps.TrackOverlay;
import fr.isima.model.Track;
import fr.isima.tools.FileUtils;

public class TrackDetails extends MapActivity
{
    private static final String  TAG              = "TrackDetails";

    private Track                track;

    private TrackProviderAdapter providerAdpt;

    private TextView             trackNameValue;
    private TextView             trackDateValue;
    private TextView             trackFreqRefreshValue;
    private TextView             trackDistRefreshValue;

    // Menu
    private static final int     DELETE           = Menu.FIRST;

    private static final int     EXPORT           = Menu.FIRST + 1;

    // Map
    private static final int     DEFAULT_ZOOM     = 15;

    // Export
    private static final String  EXPORT_DIRECTORY = "/sdcard/";
    private static final String  KML_SUFFIX       = ".kml";
    private String               exportPath;

    // Dialog
    private static final int     CONFIRM_DIALOG   = 1;

    private static final int     EXPORT_DIALOG    = 2;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.track_details);

        providerAdpt = new TrackProviderAdapter(getContentResolver());

        Intent launcher = getIntent();

        String trackId = launcher.getStringExtra(TrackSelection.TRACK_ID);

        track = providerAdpt.getTrack(Long.parseLong(trackId));

        if (track != null)
        {
           
            displayDetails(track);
        }
        else
        {
            TextView txt = new TextView(this);
            txt.setText(getResources().getString(R.string.no_tracks_found));
            addContentView(txt, new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
        }
    }

    private void displayDetails(Track track)
    {

        MapView trackMap = (MapView) findViewById(R.id.map_track);
        MapController mapCtrl = trackMap.getController();
        trackMap.setSatellite(true);
        TrackOverlay overlay = new TrackOverlay(track.getPath());

        mapCtrl.setZoom(DEFAULT_ZOOM);
        mapCtrl.animateTo(overlay.getFirst());
        trackMap.setBuiltInZoomControls(true);
        trackMap.displayZoomControls(true);
        trackMap.getOverlays().add(overlay);

        Log.d(TAG, "Display track " + track);
        trackNameValue = (TextView) findViewById(R.id.text_track_name_value);
        trackDateValue = (TextView) findViewById(R.id.text_track_date_value);
        trackFreqRefreshValue = (TextView) findViewById(R.id.text_track_freq_value);
        trackDistRefreshValue = (TextView) findViewById(R.id.text_track_dist_value);
        trackNameValue.setText(track.getName());
        trackDateValue.setText(new SimpleDateFormat(getResources().getString(
                R.string.dateformat)).format(track.getDate()));
        trackFreqRefreshValue.setText(String.valueOf(track.getFreqRefresh()));
        trackDistRefreshValue.setText(String.valueOf(track.getDistRefresh()));

        // Export
        StringBuffer buffer = new StringBuffer(EXPORT_DIRECTORY);
        buffer.append(getResources().getString(R.string.app_name));

        exportPath = buffer.toString() + "/" + track.getName() + KML_SUFFIX;

    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);

        MenuItem itemSortByName = menu.add(0, DELETE, Menu.NONE,
                R.string.delete);
        MenuItem itemSortByDate = menu.add(0, EXPORT, Menu.NONE,
                R.string.Export);

        itemSortByName.setShortcut('0', 'd');
        itemSortByDate.setShortcut('1', 'e');

        return true;
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }

    private void deleteTrack(String id)
    {
        providerAdpt.deleteTrack(Long.parseLong(id));
        Intent selection = new Intent(this, TrackSelection.class);
        startActivity(selection);
    }

    private void exportTrack()
    {
        StringBuffer buffer = new StringBuffer(EXPORT_DIRECTORY);
        buffer.append(getResources().getString(R.string.app_name));
        FileUtils.copyFile(track.getPath(), buffer.toString(), "/"
                + track.getName() + KML_SUFFIX); 
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case EXPORT:
                exportTrack();
                showDialog(EXPORT_DIALOG);
                break;

            case DELETE:
                showDialog(CONFIRM_DIALOG);
                break;

            default:
                break;
        }
        return true;
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        AlertDialog alert = null;
        switch (id)
        {
            case CONFIRM_DIALOG:
                AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(
                        this);

                String yes = getResources().getString(R.string.yes);
                String no = getResources().getString(R.string.no);
                confirmBuilder.setTitle(getResources().getString(
                        R.string.confirm_delete_title));
                confirmBuilder.setMessage("");
                confirmBuilder.setCancelable(false).setPositiveButton(yes,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                deleteTrack(track.getId());
                            }
                        }).setNegativeButton(no,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                dialog.cancel();
                            }
                        });
                alert = confirmBuilder.create();
                yes = null;
                no = null;
                break;
            case EXPORT_DIALOG:
                AlertDialog.Builder exportBuilder = new AlertDialog.Builder(
                        this);
                exportBuilder.setTitle(getResources().getString(
                        R.string.export_title));
                exportBuilder.setMessage("");
                String ok = getResources().getString(R.string.ok);
                exportBuilder.setCancelable(false).setPositiveButton(ok,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                dialog.cancel();
                            }
                        });
                alert = exportBuilder.create();
                ok = null;
                break;
            default:
                break;
        }
        return alert;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog)
    {
        switch (id)
        {
            case CONFIRM_DIALOG:
               String formatConfirm = getResources().getString(R.string.confirm_delete_track);
               String messageConfirm = String.format(formatConfirm, track.getName());
               
               AlertDialog confirmDialog = (AlertDialog) dialog;
               confirmDialog.setMessage(messageConfirm);
               
               messageConfirm = null;
               formatConfirm = null;
                break;
                
            case EXPORT_DIALOG:
                String formatExport = getResources().getString(R.string.export_track);
                String messageExport = String.format(formatExport, track.getName(), exportPath);
                
                AlertDialog exportDialog = (AlertDialog) dialog;
                exportDialog.setMessage(messageExport);
                
                messageExport = null;
                formatExport = null;
                break;
            }
    }
}
